layui.use(['form', 'layer'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery;

    //页面radio绑定选中和取消选中事件 (问题类型radio除外，不然会导致问题类型radio选择点击两次才生效)
    form.on("radio", function () {
        console.log($(this).attr("name"));
        if ($(this).attr("name").substring(0, 12) != "QuestionType") {
            var xuanzhong = $(this).attr("data-check");
            if (xuanzhong == "false") {
                $(this).attr('data-check', "true");
                $(this).prop('checked', true);
                layui.form.render();
            } else {
                $(this).attr('data-check', "false");
                $(this).prop('checked', false);
                layui.form.render();
            }
        }
    });

    $(".addOneQuestion").click(function () {
        var div = $("#divQuestion");
        var qu = $("#divQuestion .quoteBox");
        var count = Number(qu.length) + 1;
        console.log(qu);
        var proHtml = "<label>第" + count + "题</label>" +
            "<blockquote class=\"layui-elem-quote quoteBox\">" +
            "<div class=\"layui-box layui-row\" >" +
            "<label class=\"layui-form-label\">问题类型</label>" +
            "<div class=\"layui-input-block\">" +
            "<input type=\"radio\" name=\"QuestionType" + count + "\" value=\"0\" lay-filter=\"QuestionType" + count + "Filter\" title=\"单选题\" checked>" +
            "<input type=\"radio\" name=\"QuestionType" + count + "\" value=\"1\" lay-filter=\"QuestionType" + count + "Filter\" title=\"多选题\">" +
            "<input type=\"radio\" name=\"QuestionType" + count + "\" value=\"2\" lay-filter=\"QuestionType" + count + "Filter\" title=\"判断题\">" +
            "</div>" +
            "</div>" +
            "<div class=\"layui-box layui-row\">" +
            "<label class=\"layui-form-label\">题目</label>" +
            "<div class=\"layui-input-block\">" +
            "<input type=\"text\" name=\"Question\" id=\"Question" + count + "\" class=\"layui-input Question\" placeholder=\"请输入题目\" lay-verify=\"required|Question\" autocomplete=\"off\" />" +
            "</div>" +
            "</div>" +
            "<div class=\"layui-box layui-row\">" +
            "<label class=\"layui-form-label\">本题分数</label>" +
            "<div class=\"layui-input-block\">" +
            "<input type=\"text\" name=\"QuestionScore\" id=\"QuestionScore" + count + "\" class=\"layui-input Question\" placeholder=\"请输入本题分数（数字）\" lay-verify=\"required|QuestionScore\" autocomplete=\"off\" />" +
            "</div>" +
            "</div>" +
            "<div class=\"layui-box layui-row\">" +
            "<label class=\"layui-form-label addOneQuestionOption\">添加选项</label>" +
            "<div class=\"layui-input-block questionOptions\">" +
            "<input type=\"text\" name=\"Option1\" class=\"layui-input Option1\" placeholder=\"请输入选项\" lay-verify=\"required|Option\" autocomplete=\"off\" />" +
            "</div>" +
            "</div>" +
            "<div class=\"layui-box layui-row answerDiv\">" +
            "<label class=\"layui-form-label\">本题答案</label>" +
            "<div class=\"layui-input-block questionAnswers\">" +
            "<input type=\"radio\" data-check=\"false\" name=\"answer" + count + "-1\" value=\"1\" lay-filter=\"answerFilter\" title=\"1\">" +
            //"<input type=\"text\" name=\"Option\" id=\"Answer" + count + "\" class=\"layui-input answer\" placeholder=\"请输入答案，按选项单元格顺序，自1起始，如1/2/3/4\" lay-verify=\"Option\" autocomplete=\"off\" />" +
            "</div>" +
            "</div>" +
            "</blockquote>";
        $("#divQuestion").append(proHtml);
        form.render();
    });

    $(document).on("click", ".addOneQuestionOption", function () {
        var index1 = $("#divQuestion .quoteBox").index($(this).parent().parent()); //当前quoteBox是这个div中第几个
        index1 = Number(index1) + 1;
        var needAppendOption = $(this).parent().find(".layui-input-block");
        var needAppendAnswer = $(this).parent().parent().find(".answerDiv").find(".questionAnswers");
        var input = needAppendOption.find("input");
        var count = Number(input.length) + 1;
        var optionHtml = "<input type=\"text\" name=\"Option\" class=\"layui-input Option" + count + "\" placeholder=\"请输入选项\" lay-verify=\"required|Option\" autocomplete=\"off\" />";
        //本体答案radio需注意命名为当前第几题的第几个选项
        var answerHtml = "<input type=\"radio\" data-check=\"false\" name=\"answer" + index1 + "-" + count + "\" value=\"" + count + "\" lay-filter=\"answerFilter\" title=\"" + count + "\">";
        needAppendOption.append(optionHtml);
        needAppendAnswer.append(answerHtml);
        console.log(needAppendOption);
        console.log(needAppendAnswer);
        form.render();
    })

    form.on("submit(addTestPage)", function () {
        var questionBox = $("#divQuestion .quoteBox");
        var question1JsonArr = [];
        $.each(questionBox, function (i) {
            //var everyQuestionName = $(this).find('input[name="Question"]').val();
            var index = Number(i) + 1;
            var everyQuestionOptions = [];
            var everyQuestionAnswers = [];
            var everyQuestionName = $("#Question" + index).val();
            var everyQuestionScore = $("#QuestionScore" + index).val();
            var questionType = $('input[name="QuestionType' + index + '"]:checked').val();
            var optionInputs = $(this).find(".questionOptions").find('input');
            var answerInputs = $(this).find(".questionAnswers").find('input');

            $.each(optionInputs, function (i, data) {
                var optionIndex = Number(i) + 1;
                everyQuestionOptions.push({ "OptionName": $(this).val() });
            });
            $.each(answerInputs, function (i, data) {
                if ($(this).attr("data-check") == "true")
                    everyQuestionAnswers.push(Number($(this).val()));
            });
            var everyQuestionJsonObject = { "QuestionName": everyQuestionName, "Type": questionType, "QuestionScore": everyQuestionScore, "ExamOption": everyQuestionOptions, "RigthOptionIds": everyQuestionAnswers };
            question1JsonArr.push(everyQuestionJsonObject);
        });
        //console.log(JSON.stringify(question1JsonArr));

        //var question = [];
        //var option = [];
        //var answer = [];
        //var question1Name = $("#Question1").val();
        //var questionType = $('input[name="QuestionType1"]:checked').val();
        //var questionAnswer = $("#Answer1").val();
        //var inputs = $(".questionOptions1").find('input');
        //$.each(inputs, function (i, data) {
        //    console.log($(this).val() + i + data);
        //    option.push({ "OptionName": $(this).val() });
        //});
        //console.log(questionAnswer);
        //console.log(questionType);
        //var question1JsonObject = { "QuestionName": question1Name, "Type": questionType, "ExamOption": option };  //
        //var question1JsonArr = [];
        //question1JsonArr.push(question1JsonObject);
        ////answer.push(questionAnswer);
        ////获取防伪标记
        $.ajax({
            type: 'POST',
            url: '/TestPage/AddOrModify/',
            data: {
                Id: $("#Id").val(),  //主键
                TestPageName: $(".TestPageName").val(),
                LimitMin: $(".LimitTime").val(),
                LimitTimes: $(".LimitCount").val(),
                TotalScore: $(".TotalScore").val(),
                PassScore: $(".PassScore").val(),
                ExamQuestions: question1JsonArr
            },
            dataType: "json",
            headers: {
                "X-CSRF-TOKEN-Gerald": $("input[name='AntiforgeryKey_Gerald']").val()
            },
            success: function (res) {//res为相应体,function为回调函数
                var alertIndex;
                if (res.ResultCode === 0) {
                    alertIndex = layer.alert(res.ResultMsg, { icon: 1 }, function () {
                        layer.closeAll("iframe");
                        //刷新父页面
                        parent.location.reload();
                        top.layer.close(alertIndex);
                    });
                    //$("#res").click();//调用重置按钮将表单数据清空
                } else if (res.ResultCode === 102) {
                    alertIndex = layer.alert(res.ResultMsg, { icon: 5 }, function () {
                        layer.closeAll("iframe");
                        //刷新父页面
                        parent.location.reload();
                        top.layer.close(alertIndex);
                    });
                }
                else {
                    layer.alert(res.ResultMsg, { icon: 5 });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.alert('操作失败！！！' + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
            }
        });
        return false;
    });
});